<template>
	<view class="carousel-settings-container">
		<view class="carousel-settings">
			<view class="settings-header">
				<text class="settings-title">{{ type === 'desktop' ? '桌面壁纸轮播设置' : (type === 'lockscreen' ? '锁屏壁纸轮播设置' : '壁纸轮播设置') }}</text>
			</view>
			
			<view class="settings-body">
				<view class="setting-item">
					<text class="setting-label">壁纸应用范围</text>
					<view class="scope-selector">
						<picker @change="onTypeChange" :value="typeIndex" :range="wallpaperTypes" range-key="name">
							<view class="picker-view">
								<text class="type-text">{{ getTypeName }}</text>
								<text class="type-icon">🔄</text>
							</view>
						</picker>
					</view>
				</view>
				
				<view class="setting-item">
					<text class="setting-label">选择文件夹路径</text>
					<view class="folder-selector">
						<picker @change="onFolderChange" :value="selectedFolderIndex" :range="predefinedFolders" range-key="name">
							<view class="picker-view">
								<text class="folder-path">{{ folderPath || '请选择文件夹' }}</text>
								<text class="folder-icon">📁</text>
							</view>
						</picker>
					</view>
				</view>
				
				<view class="setting-item">
					<text class="setting-label">显示图片数量</text>
					<text class="image-count">{{ imageCount }}张</text>
				</view>
				
				<view class="setting-item">
					<text class="setting-label">轮播周期时间</text>
					<view class="time-selector">
						<input 
							type="number" 
							v-model.number="carouselInterval" 
							class="time-input" 
							placeholder="请输入轮播间隔(分钟)"
						/>
						<text class="time-unit">分钟</text>
					</view>
				</view>
				
				<view class="setting-item">
					<text class="setting-label">在解锁时更改壁纸</text>
					<switch 
						:checked="isEnabled" 
						@change="onStatusChange" 
						color="#007AFF"
					/>
				</view>
			</view>
			
			<view class="settings-footer">
				<button class="btn btn-save" @click="saveSettings">确定</button>
				<button class="btn btn-cancel" @click="WallpaperStore.iswallpapercarousel=false">退出</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted, computed, onUnmounted as vueOnUnmounted, watch } from 'vue';	
	import { useWallpaperStore } from '../../common/index/Wallpaper';
	
	const WallpaperStore = useWallpaperStore();
	
	// 定义壁纸类型，默认为桌面壁纸
	const type = ref(WallpaperStore.currentType);
	
	// 壁纸类型选项
	const wallpaperTypes = ref([
		{ name: '仅桌面壁纸', value: 'desktop' },
		{ name: '仅锁屏壁纸', value: 'lockscreen' },
		{ name: '同时设置桌面和锁屏', value: 'both' }
	]);
	
	// 当前选中的类型索引
	const typeIndex = ref(0);
	
	// 类型选择变化处理
	const onTypeChange = (e) => {
		const index = e.detail.value;
		typeIndex.value = index;
		const selectedType = wallpaperTypes.value[index].value;
		type.value = selectedType;
		WallpaperStore.setCurrentType(selectedType);
	};
	
	// 计算属性：获取类型名称
	const getTypeName = computed(() => {
		if (type.value === 'desktop') {
			return '仅桌面壁纸';
		} else if (type.value === 'lockscreen') {
			return '仅锁屏壁纸';
		} else if (type.value === 'both') {
			return '同时设置桌面和锁屏';
		}
		return '请选择应用范围';
	});
	
	// 从store获取当前设置
	const currentSettings = computed(() => WallpaperStore.currentSettings);
	
	// 预定义的文件夹路径
	const predefinedFolders = ref([
		{ name: '相册目录', path: '/storage/emulated/0/DCIM' },
		{ name: '图片目录', path: '/storage/emulated/0/Pictures' },
		{ name: '下载目录', path: '/storage/emulated/0/Download' },
		{ name: '自定义目录', path: '/storage/emulated/0/Wallpapers' },
	]);
	
	// 选中的文件夹索引
	const selectedFolderIndex = ref(0);
	
	// 文件夹路径
	const folderPath = ref(currentSettings.value.folderPath || '');
	
	// 图片数量
	const imageCount = ref(currentSettings.value.imageList.length || 0);
	
	// 轮播间隔时间（分钟）
	const carouselInterval = ref(currentSettings.value.carouselInterval || 5);
	
	// 是否启用
	const isEnabled = ref(currentSettings.value.isEnabled || false);
	
	// 存储图片列表
	const imageList = ref(currentSettings.value.imageList || []);
	
	// 当前显示的图片索引
	const currentImageIndex = ref(0);
	
	// 轮播定时器
	let carouselTimer = null;
	
	// 监听类型变化
	watch(type, (newType) => {
		WallpaperStore.setCurrentType(newType);
		// 更新界面数据
		folderPath.value = WallpaperStore.currentSettings.folderPath || '';
		imageList.value = WallpaperStore.currentSettings.imageList || [];
		imageCount.value = imageList.value.length;
		carouselInterval.value = WallpaperStore.currentSettings.carouselInterval || 5;
		isEnabled.value = WallpaperStore.currentSettings.isEnabled || false;
	});
	
	// 文件夹选择变化处理
	const onFolderChange = (e) => {
		const index = e.detail.value;
		selectedFolderIndex.value = index;
		const selectedFolder = predefinedFolders.value[index];
		folderPath.value = selectedFolder.path;
		
		// 扫描选定的文件夹
		scanFolderImages(folderPath.value);
	};
	
	// 选择文件夹
	const selectFolder = async () => {
		// 提示用户选择预定义的文件夹路径
		uni.showToast({
			title: '请从下拉菜单选择文件夹',
			icon: 'none',
			duration: 2000
		});
	};
	
	// 使用模拟数据
	const useMockData = () => {
		folderPath.value = predefinedFolders.value[selectedFolderIndex.value].path;
		imageCount.value = 5;
		imageList.value = Array(5).fill().map((_, i) => `${folderPath.value}/mock_image${i+1}.jpg`);
		uni.showToast({
			title: '使用模拟数据',
			icon: 'none'
		});
	};
	
	// 扫描文件夹中的图片
	const scanFolderImages = (path) => {
		try {
			if (typeof plus !== 'undefined' && plus.io) {
				plus.io.resolveLocalFileSystemURL(path, (entry) => {
					if (entry.isDirectory) {
						const reader = entry.createReader();
						reader.readEntries((entries) => {
							// 过滤出图片文件
							const imageFiles = entries.filter(entry => {
								const name = entry.name.toLowerCase();
								return name.endsWith('.jpg') || 
									   name.endsWith('.jpeg') || 
									   name.endsWith('.png') || 
									   name.endsWith('.gif') || 
									   name.endsWith('.bmp');
							});
							
							if (imageFiles.length > 0) {
								imageList.value = imageFiles.map(entry => entry.fullPath);
								imageCount.value = imageList.value.length;
								
								uni.showToast({
									title: '找到' + imageCount.value + '张图片',
									icon: 'success'
								});
							} else {
								uni.showToast({
									title: '所选文件夹中没有图片',
									icon: 'none'
								});
								useMockData();
							}
						}, (error) => {
							console.error('读取文件夹内容出错:', error);
							useMockData();
						});
					} else {
						uni.showToast({
							title: '所选项不是文件夹',
							icon: 'none'
						});
						useMockData();
					}
				}, (error) => {
					console.error('解析文件夹路径出错:', error);
					useMockData();
				});
			} else {
				// 在不支持plus.io的环境下使用模拟数据
				useMockData();
			}
		} catch (error) {
			console.error('扫描文件夹出错:', error);
			useMockData();
		}
	};
	
	// 轮播间隔变化处理
	const onIntervalChange = (e) => {
		let value = parseInt(e.detail.value);
		if (isNaN(value) || value < 1) {
			value = 1;
		} else if (value > 60) {
			value = 60;
		}
		carouselInterval.value = value;
	};
	
	// 状态变化处理
	const onStatusChange = (e) => {
		isEnabled.value = e.detail.value;
	};
	
	// 保存设置
	const saveSettings = () => {
		try {
			if (!folderPath.value) {
				uni.showModal({
					title: '提示',
					content: '请选择文件夹',
					showCancel: false
				});
				return;
			}
			
			if (imageCount.value === 0) {
				uni.showModal({
					title: '提示',
					content: '所选文件夹中没有图片',
					showCancel: false
				});
				return;
			}
			
			// 验证轮播间隔
			const interval = Number(carouselInterval.value);
			if (isNaN(interval) || interval <= 0 || interval > 60) {
				uni.showModal({
					title: '提示',
					content: '轮播间隔必须是1-60之间的数字',
					showCancel: false
				});
				return;
			}
			carouselInterval.value = interval;
			
			// 更新设置到store
			const settings = {
				folderPath: folderPath.value,
				carouselInterval: carouselInterval.value,
				isEnabled: isEnabled.value,
				imageList: imageList.value
			};
			
			try {
				// 更新store中的设置
				WallpaperStore.updateSettings(type.value, settings);
				
				// 保存设置到本地存储
				WallpaperStore.saveSettings();
				
				// 如果启用了轮播，开始轮播
				if (isEnabled.value) {
					try {
						startCarousel();
					} catch (e) {
						uni.showModal({
							title: '轮播启动失败',
							content: '无法启动轮播: ' + e.message,
							showCancel: false
						});
					}
				} else {
					stopCarousel();
				}
				
				uni.showToast({
					title: '设置已保存',
					icon: 'success',
					success: () => {
						// 延迟关闭设置界面，确保轮播有时间启动
						setTimeout(() => {
							WallpaperStore.iswallpapercarousel = false;
						}, 1500);
					}
				});
			} catch (storeError) {
				uni.showModal({
					title: '保存失败',
					content: '保存设置到存储失败: ' + storeError.message,
					showCancel: false
				});
				console.error('保存设置到store失败:', storeError);
			}
		} catch (error) {
			// 显示详细的错误信息
			uni.showModal({
				title: '保存设置失败',
				content: '错误信息: ' + (error.message || '未知错误'),
				showCancel: false
			});
			console.error('保存壁纸设置出错:', error);
		}
	};
	
	// 开始轮播
	const startCarousel = () => {
		try {
			// 清除之前的定时器
			stopCarousel();
			
			// 设置新的定时器
			carouselTimer = setInterval(() => {
				try {
					changeWallpaper();
				} catch (e) {
					console.error('轮播过程中出错:', e);
					uni.showModal({
						title: '轮播错误',
						content: '更换壁纸过程中出错: ' + e.message,
						showCancel: false
					});
				}
			}, carouselInterval.value * 60 * 1000); // 转换为毫秒
			
			// 立即更换一次壁纸
			changeWallpaper();
		} catch (e) {
			console.error('启动轮播出错:', e);
			throw e; // 将错误传递给调用者处理
		}
	};
	
	// 停止轮播
	const stopCarousel = () => {
		if (carouselTimer) {
			clearInterval(carouselTimer);
			carouselTimer = null;
		}
	};
	
	// 更换壁纸
	const changeWallpaper = () => {
		try {
			if (imageList.value.length === 0) {
				uni.showModal({
					title: '无法更换壁纸',
					content: '没有可用的图片',
					showCancel: false
				});
				return;
			}
			
			// 随机选择一张图片
			const randomIndex = Math.floor(Math.random() * imageList.value.length);
			currentImageIndex.value = randomIndex;
			
			const imagePath = imageList.value[randomIndex];
			
			// 检查环境和API可用性
			if (typeof plus !== 'undefined') {
				try {
					// 使用安卓系统API设置壁纸(仅安卓平台)
					if (plus.os.name.toLowerCase() === 'android') {
						setAndroidWallpaper(imagePath);
					} else if (plus.os.name.toLowerCase() === 'ios') {
						// iOS不支持直接设置壁纸，提示用户手动设置
						showManualWallpaperInstructions(imagePath);
					} else {
						uni.showModal({
							title: '不支持的平台',
							content: '当前平台不支持自动设置壁纸',
							showCancel: false
						});
					}
				} catch (e) {
					console.error('调用设置壁纸API失败:', e);
					uni.showModal({
						title: '设置壁纸失败',
						content: '无法调用系统API: ' + (e.message || '未知错误'),
						showCancel: false
					});
					
					// 回退到提示用户手动设置
					showManualWallpaperInstructions(imagePath);
				}
			} else {
				uni.showModal({
					title: '功能不可用',
					content: '当前环境不支持设置壁纸',
					showCancel: false
				});
			}
		} catch (error) {
			console.error('更换壁纸出错:', error);
			uni.showModal({
				title: '更换壁纸失败',
				content: '错误信息: ' + (error.message || '未知错误'),
				showCancel: false
			});
		}
	};
	
	// 在Android上设置壁纸
	const setAndroidWallpaper = (imagePath) => {
		try {
			// 导入需要的Android类
			const Context = plus.android.importClass("android.content.Context");
			const WallpaperManager = plus.android.importClass("android.app.WallpaperManager");
			const File = plus.android.importClass("java.io.File");
			const FileInputStream = plus.android.importClass("java.io.FileInputStream");
			const Uri = plus.android.importClass("android.net.Uri");
			const Intent = plus.android.importClass("android.content.Intent");
			const Build = plus.android.importClass("android.os.Build");
			
			// 获取当前应用的Context
			const main = plus.android.runtimeMainActivity();
			const context = main;
			
			// 获取Android SDK版本号（数字形式）
			const sdkInt = Build.VERSION.SDK_INT;
			console.log('Android SDK版本:', sdkInt);
			
			// 检查是否有权限直接设置壁纸
			try {
				// 尝试直接设置壁纸
				const wallpaperManager = WallpaperManager.getInstance(context);
				
				// 使用文件流读取图片
				const imageFile = new File(imagePath.replace('file://', ''));
				
				// 设置桌面壁纸
				if (type.value === 'desktop' || type.value === 'both') {
					const deskFis = new FileInputStream(imageFile);
					wallpaperManager.setStream(deskFis);
					deskFis.close();
				}
				
				// 设置锁屏壁纸(Android 7.0+支持，对应API 24+)
				if (type.value === 'lockscreen' || type.value === 'both') {
					try {
						// 尝试三种不同的API方式设置锁屏壁纸
						const lockFis = new FileInputStream(imageFile);
						
						// 方式1：使用FLAG_LOCK标志（Android 7.0+）
						if (sdkInt >= 24) {
							try {
								// 获取FLAG_LOCK常量值
								const FLAG_LOCK = WallpaperManager.FLAG_LOCK;
								// 设置锁屏壁纸
								wallpaperManager.setStream(lockFis, null, true, FLAG_LOCK);
								console.log('使用FLAG_LOCK方式设置锁屏壁纸成功');
							} catch (flagError) {
								console.error('使用FLAG_LOCK方式设置失败:', flagError);
								
								// 尝试方式2：使用锁屏专用API
								try {
									// 重新打开文件流
									lockFis.close();
									const newFis = new FileInputStream(imageFile);
									// 尝试使用setStreamLock方法
									if (typeof wallpaperManager.setStreamLock === 'function') {
										wallpaperManager.setStreamLock(newFis);
										console.log('使用setStreamLock方式设置锁屏壁纸成功');
										newFis.close();
									} else {
										throw new Error('setStreamLock方法不可用');
									}
								} catch (lockError) {
									console.error('使用setStreamLock方式设置失败:', lockError);
									throw lockError;
								}
							}
						} else {
							// 低版本使用反射或其他兼容方法尝试设置锁屏壁纸
							try {
								// 通过反射尝试调用非公开API
								const Class = plus.android.importClass('java.lang.Class');
								const wallpaperManagerClass = wallpaperManager.getClass();
								const setStreamMethod = wallpaperManagerClass.getDeclaredMethod('setBitmap', plus.android.importClass('android.graphics.Bitmap'), null, true, 2);
								setStreamMethod.setAccessible(true);
								
								// 将文件转为Bitmap
								const BitmapFactory = plus.android.importClass('android.graphics.BitmapFactory');
								const bitmap = BitmapFactory.decodeFile(imagePath.replace('file://', ''));
								
								// 调用方法
								setStreamMethod.invoke(wallpaperManager, bitmap, null, true, 2);
								console.log('使用反射方式设置锁屏壁纸成功');
							} catch (reflectError) {
								console.error('使用反射设置锁屏壁纸失败:', reflectError);
								
								// 如果所有方式都失败，则尝试使用系统壁纸设置器
								uni.showModal({
									title: '锁屏壁纸设置',
									content: '您的系统需要手动设置锁屏壁纸，是否打开系统设置？',
									success: (res) => {
										if (res.confirm) {
											// 使用系统壁纸设置器
											try {
												// 创建Intent调用系统壁纸设置
												const intent = new Intent(Intent.ACTION_ATTACH_DATA);
												const imageUri = Uri.parse(imagePath);
												intent.setDataAndType(imageUri, "image/*");
												intent.putExtra("mimeType", "image/*");
												intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
												intent.addCategory(Intent.CATEGORY_DEFAULT);
												main.startActivityForResult(intent, 2);
											} catch (err) {
												showManualWallpaperInstructions(imagePath);
											}
										}
									}
								});
							}
						}
						
						// 关闭锁屏文件流
						try {
							if (!lockFis.isClosed()) {
								lockFis.close();
							}
						} catch (e) {
							// 忽略关闭流的错误
						}
						
					} catch (lockScreenError) {
						console.error('设置锁屏壁纸失败:', lockScreenError);
						if (type.value === 'lockscreen') {
							uni.showModal({
								title: '锁屏壁纸设置失败',
								content: '无法自动设置锁屏壁纸，请尝试使用系统壁纸设置',
								showCancel: false
							});
						}
					}
				}
				
				uni.showToast({
					title: '壁纸已设置',
					icon: 'success'
				});
				
			} catch (directError) {
				console.error('直接设置壁纸失败:', directError);
				
				// 如果直接设置失败，使用系统壁纸选择器
				try {
					// 创建Intent调用系统壁纸设置
					const intent = new Intent(Intent.ACTION_ATTACH_DATA);
					const imageUri = Uri.parse(imagePath);
					intent.setDataAndType(imageUri, "image/*");
					intent.putExtra("mimeType", "image/*");
					intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					intent.addCategory(Intent.CATEGORY_DEFAULT);
					intent.setAction(Intent.ACTION_ATTACH_DATA);
					
					// 启动系统壁纸设置Activity
					main.startActivityForResult(intent, 2);
					
					uni.showToast({
						title: '请通过系统设置壁纸',
						icon: 'none',
						duration: 3000
					});
				} catch (intentError) {
					console.error('启动系统壁纸设置失败:', intentError);
					showManualWallpaperInstructions(imagePath);
				}
			}
		} catch (e) {
			console.error('Android设置壁纸出错:', e);
			uni.showModal({
				title: '设置壁纸失败',
				content: '无法使用Android API: ' + (e.message || '未知错误'),
				showCancel: false
			});
			
			// 提示用户手动设置
			showManualWallpaperInstructions(imagePath);
		}
	};
	
	// 显示手动设置壁纸的说明
	const showManualWallpaperInstructions = (imagePath) => {
		uni.showModal({
			title: '请手动设置壁纸',
			content: '无法自动设置壁纸，请保存图片后，通过系统设置手动设置壁纸。是否保存当前图片到相册？',
			confirmText: '保存图片',
			success: (res) => {
				if (res.confirm) {
					// 保存图片到相册
					uni.saveImageToPhotosAlbum({
						filePath: imagePath,
						success: () => {
							uni.showToast({
								title: '已保存到相册',
								icon: 'success'
							});
						},
						fail: (err) => {
							uni.showModal({
								title: '保存失败',
								content: '保存图片失败: ' + JSON.stringify(err),
								showCancel: false
							});
						}
					});
				}
			}
		});
	};
	
	// 监听解锁事件
	const listenUnlockEvent = () => {
		// 使用uni-app的事件系统监听应用从后台恢复到前台的事件
		uni.onAppShow(() => {
			if (isEnabled.value) {
				changeWallpaper();
			}
		});
	};
	
	// 监听组件挂载
	onMounted(() => {
		// 加载store中的设置
		WallpaperStore.loadSettings();
		
		// 更新本地数据
		folderPath.value = currentSettings.value.folderPath || '';
		imageList.value = currentSettings.value.imageList || [];
		imageCount.value = imageList.value.length;
		carouselInterval.value = currentSettings.value.carouselInterval || 5;
		isEnabled.value = currentSettings.value.isEnabled || false;
		
		// 初始化类型索引
		if (type.value === 'desktop') {
			typeIndex.value = 0;
		} else if (type.value === 'lockscreen') {
			typeIndex.value = 1;
		} else if (type.value === 'both') {
			typeIndex.value = 2;
		}
		
		// 在组件挂载时就检查是否需要启动轮播
		if (isEnabled.value) {
			// 确保延迟启动，等待组件完全挂载
			setTimeout(() => {
				startCarousel();
				console.log('轮播已启动，间隔:', carouselInterval.value, '分钟');
			}, 500);
		}
		
		listenUnlockEvent();
	});
	
	// 组件卸载时停止轮播
	vueOnUnmounted(() => {
		stopCarousel();
	});
</script>

<style>
.carousel-settings-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	/* background-color: rgba(0, 0, 0, 0.5); */
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 999;
}

.carousel-settings {
	width: 90%;
	background-color: #fff;
	border-radius: 15rpx;
	overflow: hidden;
}

.settings-header {
	padding: 30rpx;
	background-color: #f8f8f8;
	border-bottom: 1px solid #eee;
}

.settings-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	text-align: center;
}

.settings-body {
	padding: 30rpx;
}

.setting-item {
	margin-bottom: 30rpx;
	display: flex;
	flex-direction: column;
}

.setting-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 15rpx;
}

.folder-selector, .scope-selector {
	display: flex;
	justify-content: space-between;
	align-items: center;
	border: 1px solid #ddd;
	border-radius: 8rpx;
	padding: 15rpx;
	background-color: #f9f9f9;
}

.folder-path, .type-text {
	font-size: 26rpx;
	color: #666;
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.folder-icon, .type-icon {
	font-size: 32rpx;
	margin-left: 10rpx;
}

.image-count {
	font-size: 26rpx;
	color: #666;
}

.time-selector {
	display: flex;
	align-items: center;
}

.time-input {
	height: 60rpx;
	border: 1px solid #ddd;
	border-radius: 8rpx;
	padding: 0 20rpx;
	width: 200rpx;
	font-size: 26rpx;
}

.time-unit {
	font-size: 26rpx;
	color: #666;
	margin-left: 10rpx;
}

.settings-footer {
	display: flex;
	padding: 20rpx;
	border-top: 1px solid #eee;
}

.btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	font-size: 28rpx;
	border-radius: 8rpx;
}

.btn-save {
	background-color: #007AFF;
	color: #fff;
	margin-right: 10rpx;
}

.btn-cancel {
	background-color: #f5f5f5;
	color: #333;
	margin-left: 10rpx;
}

.picker-view {
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
}
</style>